<template>
	<e-navbar autoBack bgColor="transparent"></e-navbar>
	<view class="page" :style="[AppSkinVar]">
		<view v-if="isEmpty">
			<empty :icon="$staticPath('default_img.png')" :show="true" height="280rpx">
				<view class="text-center e-font-26 c-regular e-m-t-8">{{ $t('classify.该商品已下架') }}~</view>
			</empty>
		</view>
		<view v-else>
			<e-loading-page :loading="loading" zIndex="10075"  >
				<template #icon>
					<loader ></loader>
				</template>
			</e-loading-page>
			<!-- 商品信息 -->
			<view class="e-m-b-20">
				<nearby-goods-info :info="goodsInfo" :goodsId="goodsId"></nearby-goods-info>
			</view>
			<view class="e-m-b-20" v-if="timeCardList.length">
				<time-card :list="timeCardList" :primary="AppSkin.primary" :storeInfo="storeInfo"
					:price="checkInfo?.price" />
			</view>


			<view class="e-p-20">
				<!-- 店铺信息 -->
				<view class="e-m-b-20">
					<StoreInfo :storeInfo="storeInfo"></StoreInfo>
				</view>
				<view class="e-p-36 e-flex bg-white e-m-b-20" @tap="popupShow = true">
					<text class=" e-m-r-44 c-34">{{ $t('classify.规格') }}</text>
					<view class="e-flex-1  ">{{ checkInfo?.skuSpec || $t('classify.请选择规格与数量') }}</view>
					<image class="img-36" :src="$staticPath('layout/basics/right_arrow.png')"></image>
				</view>
				<!-- 套餐详情 -->
				<MealDetail :verifyDetail="verifyDetail"></MealDetail>
				<!-- 使用规则 -->
				<MealRules :verifyRule="verifyRule"></MealRules>
				<!-- 用户评价 -->
				<Appraise :evaluationList="evaluationList" :storeId="storeId" :storeInfo="storeInfo"></Appraise>
				<view class="" style="height: 56px;">

				</view>
				<!-- 底部操作按钮 -->
				<bottomButton :goodsInfo="goodsInfo" @buy="popupShow = true" @update="initGoodsInfo"></bottomButton>
				<sku-popup v-model:info="skuInfo" :goodsInfo="goodsInfo" v-model:goodsNum="goodsNum" :primary="AppSkin.primary"
					v-model:checkInfo="checkInfo" :show="popupShow" @skuChange="handleSkuChange"
					@close="() => (popupShow = false)" @buy="buy"></sku-popup>
			</view>
		</view>
	</view>
</template>

<script setup lang="ts">
	import { ref, computed } from 'vue'
	import nearbyGoodsInfo from './child/goodsInfo.vue'
	import {
		getGoodsSkuDetail,
		getGoodsTimeCardList,
		getStoreGoodsInfo,
		getNearbyStoreDetail,
		getStoreEvaluationList
	} from '@/common/request/api'
	import {
		useCurrentInstance
	} from '@/common/hooks'
	import type { StoreGoodsDetail, GoodsSkuDetail, GoodsSkuSpecificationItem, NearbyStoreInfo, StoreEvaluateItem, GoodsTimeCardItem } from '@/common/request/api'
	import bottomButton from './child/bottomButton.vue'
	import StoreInfo from './child/storeInfo.vue'
	import MealDetail from './child/mealDetail.vue'
	import MealRules from './child/mealRules.vue'
	import Appraise from './child/appraise.vue'
	import skuPopup from './child/skuPopup.vue'
	import timeCard from './child/timeCard.vue'
	// #ifdef MP-WEIXIN
	import { sceneParamsToObj } from '@/common/utils'
	// #endif
	// #ifdef PRIVATE || SUBSCRIPTION
	import { mpShareInit } from '@/common/utils'
	import type { MpShare } from '@/common/utils'
	import { getShareLink } from '@/common/wxInit'
	// #endif
	import {
		onLoad,
		onShow
	} from '@dcloudio/uni-app'

	const props = defineProps<{
		scene ?: string
		id ?: string
	}>()

	const ctx = useCurrentInstance()

	let pageParams : Record<string, any> = {}
	const goodsId = ref('')

	const loading = ref(true)
	// 商品是否已下架
	const isEmpty = ref(false)


	const goodsInfo = ref<StoreGoodsDetail>({
		deliveryBillingMode: 1,
		deliveryFeeUnified: 0,//统一配送费(0则是包邮)
		deliveryMode: '', //支持的发货方式，包含哪个就支持哪个 1快递 2自提 3-闪送 4-核销 5-配送 
		distributionType: 0,
		evaluateCount: 0,
		hasCollected: 0,
		hasOwn: 0,
		hasWholesalePricing: 0,
		id: '',
		minimumPurchaseQty: 0,
		maxNumber: 0,
		describes:'',
		name: '',
		price: 0,
		productCode: '',
		shareMsg: '',
		state: 4,
		stockSold: 0,
		storeDeliveryScore: 5,
		storeDescScore: 5,
		storeHasOwn: 0,
		storeId: '',
		storeLogo: '',
		storeName: '',
		storeProductCount: 5,
		storeServiceScore: 5,
		subareaId: '',
		type: 1,
		description: {
			detailRichTextMobile : '',
			detailRichTextPc : '',
			imgUrls : '',
			videoUrl : '',
		},
		activity: {},
		productType: 1
	})

	const storeId = computed(() => goodsInfo.value.storeId)
	const storeInfo = ref<NearbyStoreInfo>()

	const checkInfo = ref<GoodsSkuSpecificationItem|undefined>(undefined)//商品选中的sku
	const skuInfo = ref<GoodsSkuDetail>({
		id:-1,
		productSkuSpecifications: [],
		productSkus: []
	})
	// 套餐详情
	const verifyDetail = computed(() => {
		if (goodsInfo.value?.description?.verifyDetail) {
			return JSON.parse(goodsInfo.value.description.verifyDetail)
		}
		return undefined
	})
	// 使用规则
	const verifyRule = computed(() => {
		if (goodsInfo.value?.description?.verifyRule) {
			return JSON.parse(goodsInfo.value.description.verifyRule)
		}
		return undefined
	})

	const initGoodsInfo = async () => {
		let detail = await getStoreGoodsInfo({
			id: goodsId.value
		})

		if (detail.data.state !== 3) {
			isEmpty.value = true
			return
		}
		goodsInfo.value = detail.data
	}


	const shareInit = () => {
		let imgUrls = goodsInfo.value?.description?.imgUrls ? goodsInfo.value?.description?.imgUrls.split(',')[0] : ''
		
		// #ifdef APP-PLUS
		uni.$endless.mpShare = {
			title: goodsInfo.value.name,
			path: '',
			appDesc: goodsInfo.value.shareMsg || '',
			imageUrl: ctx.$fullLink(imgUrls),
			appParams: pageParams
		}
		// #endif

		// #ifdef MP-WEIXIN||MP-ALIPAY
		uni.$endless.mpShare = {
			title: goodsInfo.value.name,
			path: '', // 默认为当前页面路径
			imageUrl: ctx.$fullLink(imgUrls)
		}
		
		// #endif
		// #ifdef PRIVATE || SUBSCRIPTION
		uni.$endless.mpShare = {
			title: goodsInfo.value.name,
			link: getShareLink(),
			desc: goodsInfo.value.shareMsg || '',
			imgUrl: ctx.$fullLink(imgUrls)
		}
		mpShareInit(uni.$endless.mpShare as MpShare)
		// #endif
	}

	const evaluationList = ref<StoreEvaluateItem[]>([])
	const goodsNum = ref(1)
	const popupShow = ref(false)

	const timeCardList = ref<GoodsTimeCardItem[]>([])

	const handleSkuChange = () => {

		if (!checkInfo.value?.id) return
		getGoodsTimeCardList({
			skuId: checkInfo.value.id
		}).then(res => {
			timeCardList.value = res.data
		})

	}

	const buy = () => {
		popupShow.value = false
		if (goodsInfo.value.productType === 2) {
			// 服务商品，走预约页面
			ctx.$goTo('/pages/classify/reservation/index', {
				skuId: checkInfo.value?.id,
				qty: goodsNum.value,
			})
			return
		}
		// 配送改版 新增字段receivingType
		const deliveryMode = goodsInfo.value.deliveryMode?.split(',')
		let _receivingType = '2'
		if (deliveryMode) {
			if (deliveryMode.includes('3')) {
				_receivingType = '3'
			} else if (deliveryMode.includes('6')) {
				_receivingType = '6'
			} else {
				_receivingType = deliveryMode[0]
			}
		}
		ctx.$goTo('/pages/systemPay/goods/previewOrder', {
			receivingType: _receivingType,
			type: 1,
			skuId: checkInfo.value?.id,
			qty: goodsNum.value,
		})
	}

	onLoad(() => {
		let query = { ...props }
		// #ifdef MP-WEIXIN
		if (props.scene) {
			query = sceneParamsToObj(props.scene)
		}
		// #endif
		pageParams = query
		if (query.id) goodsId.value = query.id
	})


	onShow(async () => {



		if (goodsId.value) {
			loading.value = true


			try {

				await initGoodsInfo()

				if (storeId.value) {
					getNearbyStoreDetail(storeId.value).then(res => {
						storeInfo.value = res.data
					})
					getStoreEvaluationList({
						pageSize: 1,
						pageNum: 1,
						storeId: storeId.value,
					}).then(res => {
						evaluationList.value = res.rows
					})
				}
				loading.value = false
				getGoodsSkuDetail({ productId: goodsId.value }).then(res => {
					skuInfo.value = res.data
				})
				// 页面分享的初始化
				shareInit()
			} catch (e) {
				console.log(e)
			}
		}

	})
</script>

<style lang="scss" scoped>
	.page {
		min-height: 100vh;
	}
</style>